


function getPropertyEditer(inputtype, fieldName, storesql, selval, valCase) {
	if (inputtype == 'textarea') return "<textarea style='width:200px'></textarea>"
	else if (inputtype == 'text') return "<input style='width:200px'></input>"
	else if (inputtype == 'select')  return buildFieldSelect(fieldName, storesql, selval, valCase)
	else if (inputtype == 'radio')  return buildFieldRadio(fieldName, storesql, selval, valCase)
	else if (inputtype == 'checkbox')  return buildFieldCheckbox(fieldName, storesql, selval, valCase)
	else return selval;
}
var buildFieldSelect = function (fieldName, storesql, selval, valCase) {
	var html = '<select field="' + fieldName + '">';
	var options = storesql.split(",");
	for (var i = 0; i < options.length; i++) {
		var isChecked = "";
		if (options[i] == selval) isChecked = 'selected=true';
		if (!selval) isChecked = "";
		var optionVal = options[i] || "";
		if (valCase == "upper")
			optionVal = optionVal.toUpperCase();
		else if (valCase == "lower")
			optionVal = optionVal.toLowerCase();
		html += '<option value ="' + options[i] + '"' + isChecked + '>' + optionVal + '</option>'
	}
	;
	html += " </select>";
	return html;
};
var buildFieldRadio = function (fieldName, storesql, selval, radioName) {
	var options = this.getOptions(storesql, selval, 'radio');
	var html = '';
	for (var i = 0; i < options.length; i++) {
		var isChecked = "";
		if (options[i].selected) isChecked = ' checked="checked"';
		html += '<input field = "' + fieldName + '" name="' + radioName + '" type="radio" value ="' + options[i].id + '"' + isChecked + '>' + options[i].name + '</option>'
	}
	;
	return html;
};
var buildFieldCheckbox = function (fieldName, storesql, selval, radioName) {
	var options = this.getOptions(storesql, selval, 'checkbox');
	var html = '';
	for (var i = 0; i < options.length; i++) {
		var isChecked = "";
		if (options[i].selected) isChecked = ' checked="checked"';

		html += '<input field = "' + fieldName + '" name="' + fieldName + '" type="checkbox" value ="' + options[i].id + '"' + isChecked + '>' + options[i].name + '</input>'
	}
	;
	return html;
};
var getOptions = function (storesql, selVal, elementType) {  ///根据配置返回一个数组，包含key,value,当前选中的值
	var self = this;
	var allOptions = [];//{id,name}
	var isSelVal = function (optionsId) {
		if (selVal && elementType && elementType == 'checkbox') {
			var checkVals = selVal.split(",");
			var checkSel = false;
			for (var m in checkVals) {
				if (checkVals[m] && optionsId && (checkVals[m].toString().trim() == optionsId.trim())) {
					checkSel = true;
					break;
				}
			}
			return checkSel;
		} else {
			return selVal && optionsId ? (selVal.toString().trim() == optionsId.trim()) : false;
		}
	};
	if (storesql) {
		if (storesql.toLowerCase().indexOf('select ') != -1 &&
			storesql.toLowerCase().indexOf(' from ') != -1) {
			var store = ai.getStoreData(self.rebuildSQL(storesql));
			var attrNames = store && store.length > 0 ? ai.getJsonAttrName(store[0]) : '';
			for (var i = 0; store && i < store.length; i++) {
				var r = store[i];
				var optionRec = {};
				for (var k in r) {
					optionRec[k.toLowerCase()] = r[k];
				}
				optionRec.id = r[attrNames[0]];
				optionRec.name = r[attrNames.length == 1 ? attrNames[0] : attrNames[1]];
				optionRec.selected = isSelVal(r[attrNames[0]]);
				allOptions.push(optionRec);
			}
		} else if (storesql.indexOf("|") >= 1) { //1,中国|2,美国
			var tmpArray = storesql.split("|");
			for (var i = 0; i < tmpArray.length; i++) {
				var option = tmpArray[i];
				allOptions.push({
					id: option.split(",")[0]
					, name: option.split(",")[1]
					, selected: isSelVal(option.split(",")[0])
				});
			}
		} else if (storesql) {
			var tmpArray = storesql.split(",");
			for (var i = 0; i < tmpArray.length; i++) {
				allOptions.push({
					id: tmpArray[i]
					, name: tmpArray[i]
					, selected: isSelVal(tmpArray[i])
				});
			}
		}
	}
	return allOptions;
};

function buildApiInPara(apiid) {

	var apiParaSql = "SELECT API_ID, PARA_DIR, PARA_NAME, PARA_CNNAME, PARA_REMARK, ALLOW_NULL, PARA_DEFAULT, PARA_SEQ, INPUTTYPE, INPUTPARA, ISNULL, SELMODEL, TABSHEET, DEPENDENCIES, CHECKITEMS, CFG_JSON FROM do_api_para where API_ID='" + apiid + "' and PARA_DIR='in'";
	apiInParaStore = new AI.JsonStore({
		sql: apiParaSql,
		pageSize: -1,
		key: 'API_ID',
		table: "do_api_para"
	});
	if (apiInParaStore.getCount() == 0) {
		for (var i = 0; i < 5; i++) {

			var newR = apiInParaStore.getNewRecord();
			newR.set("API_ID", apiid);
			newR.set("PARA_DIR", "in");
			newR.set("PARA_NAME", "");
			newR.set("PARA_CNNAME", "");
			newR.set("PARA_REMARK", "");
			newR.set("PARA_SEQ", i);
			apiInParaStore.add(newR);
		}
	}
	;

	var instgridcfg = {
		id: 'apiparaIn',
		split: '',
		region: 'center',
		title: '',
		width: 120,
		height: 120,
		cfgcode: '',
		subtype: 'edgrid', //grid,ghgrid,expandgrid,edgrid,groupgrid,
		store: apiInParaStore,
		columns: [
			{"header": "序号", "width": 41, "sortable": true, "dataIndex": "PARA_SEQ"},
			{"header": "参数名", "width": 91, "sortable": true, "dataIndex": "PARA_NAME", editable: true},
			{"header": "中文名", "width": 191, "sortable": true, "dataIndex": "PARA_CNNAME", editable: true},
			{
				"header": "参数类型",
				"width": 81,
				"sortable": true,
				"dataIndex": "TABSPACE",
				editable: true,
				editType: "combox",
				storesql: '整形,字符类型,时间(yyyy-mm-dd)'
			},
			{"header": "默认值", "width": 81, "sortable": true, "dataIndex": "EFF_DATE", editable: true},
			{"header": "参数说明", "width": 181, "sortable": true, "dataIndex": "PARA_REMARK", editable: true}
		],
		containerId: apiid + '_in_fieldset'
	};
	var instTabGrid = new AI.Grid(instgridcfg);
};
function buildApiOutPara(apiid) {

	var apiParaSql = "SELECT API_ID, PARA_DIR, PARA_NAME, PARA_CNNAME, PARA_REMARK, ALLOW_NULL, PARA_DEFAULT, PARA_SEQ, INPUTTYPE, INPUTPARA, ISNULL, SELMODEL, TABSHEET, DEPENDENCIES, CHECKITEMS, CFG_JSON FROM do_api_para where API_ID='" + apiid + "' and PARA_DIR='out'";
	apiParaOutStore = new AI.JsonStore({
		sql: apiParaSql,
		pageSize: -1,
		key: 'API_ID',
		table: "do_api_para"
	});
	if (apiParaOutStore.getCount() == 0) {
		for (var i = 0; i < tabColStore.getCount(); i++) {
			var r = tabColStore.getAt(i);

			var newR = apiParaOutStore.getNewRecord();
			newR.set("API_ID", apiid);
			newR.set("PARA_DIR", "out");
			newR.set("PARA_NAME", r.get("COLNAME"));
			newR.set("PARA_CNNAME", r.get("COLCNNAME"));
			newR.set("PARA_REMARK", r.get("REMARK"));

			newR.set("PARA_SEQ", i);
			apiParaOutStore.add(newR);
		}
		apiParaOutStore.commit();
	}
	;

	var instgridcfg = {
		id: 'apiparaIn',
		split: '',
		region: 'center',
		title: '',
		width: 120,
		height: 120,
		cfgcode: '',
		subtype: 'edgrid', //grid,ghgrid,expandgrid,edgrid,groupgrid,
		store: apiParaOutStore,
		columns: [
			{"header": "序号", "width": 91, "sortable": true, "dataIndex": "PARA_SEQ"},
			{"header": "参数名", "width": 91, "sortable": true, "dataIndex": "PARA_NAME", editable: true},
			{"header": "中文名", "width": 191, "sortable": true, "dataIndex": "PARA_CNNAME", editable: true},
			{
				"header": "参数类型",
				"width": 81,
				"sortable": true,
				"dataIndex": "TABSPACE",
				editable: true,
				editType: "combox",
				storesql: '整形,字符类型,时间(yyyy-mm-dd)'
			},
			{"header": "安全控制", "width": 81, "sortable": true, "dataIndex": "EFF_DATE", editable: true},
			{"header": "参数说明", "width": 81, "sortable": true, "dataIndex": "PARA_REMARK", editable: true}
		],
		containerId: apiid + '_out_fieldset'
	};
	var instTabGrid = new AI.Grid(instgridcfg);
};
function buildColGrid() {///字段结构信息

	var tabcolsql = "select col_seq,lcase(colname) colname,colcnname,lcase(datatype) datatype,length,remark,isnullable,key_seq from COLUMN_VAL where xmlid='" + xmlid + "' order by col_seq";
	tabColStore = new AI.JsonStore({
		sql: tabcolsql,
		pageSize: -1,
		key: 'DATANAME',
		dataSource: 'METADB'
	});

	var gridcfg = {
		id: 'cfgtabColgrid',
		split: '',
		region: 'center',
		title: '',
		width: 120,
		height: 120,
		cfgcode: '',
		subtype: 'edgrid', //grid,ghgrid,expandgrid,edgrid,groupgrid,
		store: tabColStore,
		columns: [
			{"header": "编号", "width": 70, "sortable": true, "dataIndex": "COL_SEQ"},
			{
				"header": "字段名", "width": 130, "sortable": true, "dataIndex": "COLNAME", render1: function (rec) {
				return "<b><font color=blue size=5>" + rec.get('COLNAME') + "</font></b>";
			}
			},
			{"header": "中文名", "width": 130, "sortable": true, "dataIndex": "COLCNNAME", editable: true},
			{
				"header": "敏感级别",
				"width": 81,
				"sortable": true,
				"dataIndex": "RIGHTLEVEL",
				editable: true,
				editType: "combox",
				storesql: '无,一级敏感,二级敏感,不开放'
			},
			{
				"header": "安全策略",
				"width": 81,
				"sortable": true,
				"dataIndex": "PROTECTTYPE",
				editable: true,
				editType: "combox",
				storesql: '存储加密,查询时加密'
			},
			{
				"header": "加密算法",
				"width": 81,
				"sortable": true,
				"dataIndex": "DESFUN",
				editable: true,
				editType: "combox",
				storesql: 'DES静态加密,公钥加密,使用者私钥加密'
			},
			{
				"header": "标准化程度",
				"width": 81,
				"sortable": true,
				"dataIndex": "STDTYPE",
				editable: true,
				editType: "combox",
				storesql: '无,已经标准化,查询时标准转化'
			},
			{"header": "标准化映射", "width": 81, "sortable": true, "dataIndex": "STDCODE", editable: true},
			{
				"header": "质量可信度",
				"width": 81,
				"sortable": true,
				"dataIndex": "DQLEVEL",
				editable: true,
				editType: "combox",
				storesql: '差,一般,好'
			},
			{
				"header": "计量模式",
				"width": 81,
				"sortable": true,
				"dataIndex": "LOGTYPE",
				editable: true,
				editType: "combox",
				storesql: '独立计量'
			},
			{"header": "详细说明", "width": 130, "sortable": true, "dataIndex": "COLCNNAME", editable: true}
		],
		containerId: 'tabColgrid'
	};
	var dataGrid = new AI.Grid(gridcfg);
};
function buildCardInfo(options) {
	var htmltpl = '<div class="panel panel-default"><div class="panel-body" style="color:white;min-height:120px;background: #4cb6cb;"><h4>{objname}</h4><p>{cnname}</p><p>{dbname}</p></div><div class="panel-footer bg-light lter text-center"><div class="row pull-out"><div class="col-xs-4"><a href="#"   style="color:red"><div class="padder-v "><span class="m-b-xs h5 block">{usernum}</span><small class="text-muted ">使用人数</small></div></a></div><div class="col-xs-4 dk"><a href="#"  style="color:red"><div class="padder-v "><span class="m-b-xs h5 block">{usertimes}</span><small class="text-muted ">使用次数</small></div></a></div><div class="col-xs-4"><a href="#"   style="color:red"><div class="padder-v "><span class="m-b-xs h5 block"><span class="glyphicon glyphicon-thumbs-up"></span></span><small class="text-muted ">评价</small></div></a></div></div></div></div>';
	var html = htmltpl.replace("{objname}", options.objname)
		.replace("{cnname}", options.cnname)
		.replace("{dbname}", options.dbname)
		.replace("{usernum}", options.usernum)
		.replace("{usertimes}", options.usertimes);

	$("#" + options.containerId).empty().append(html);
};
function buildTabBaseInfo(data) {
	for (key in data) {
		$("#" + key).html(data[key]);
	}
}

function buildTabAssertConfig() {
	var dsTabAssertInfo = new AI.JsonStore({
		sql: "select * from metaobjmodel_def   where objtype='TAB' and parentcode='assert' order by ordseq",
		pageSize: -1
	});
	var gridcfg = {
		id: 'cfgtabassertinfo',
		split: '',
		region: 'center',
		title: '',
		width: 120,
		height: 120,
		cfgcode: '',
		subtype: 'edgrid', //grid,ghgrid,expandgrid,edgrid,groupgrid,
		store: dsTabAssertInfo,
		columns: [
			{
				"header": "序号", "width": 40, "sortable": true, "dataIndex": "ORDSEQ", render: function (r, val) {
				return "<b>" + val + "</b>"
			}
			},
			{
				"header": "资产化配置项", "width": 120, "sortable": true, "dataIndex": "PARANAME", render: function (r, val) {
				return "<b>" + val + "</b>"
			}
			},
			{
				"header": "配置值", "width": 230, "sortable": true, "dataIndex": "COLNAME", render: function (rec, val) {
				return getPropertyEditer(rec.get("REFNAME"), rec.get("PARACODE"), rec.get("PARATEXT"))
			}
			},
			{"header": "说明", "width": 230, "sortable": true, "dataIndex": "REMARK"}
		],
		containerId: 'tabassertinfo'
	};
	var dataGrid = new AI.Grid(gridcfg);
}
function buildApiInstance() {
	var listtpl = '<li class="list-group-item active"><div class="media"><span class="pull-left thumb-sm">{apitype}</span><div class="media-body"><div><a href="#{apiid}"  role="tab" data-toggle="tab" >{apname}</a></div><small class="text-muted">{REMARK}</small></div></div></li>';
	var apibodyTpl = ['<div role="tabpanel" class="tab-pane fade" id="{apiid}">',
		'      			  <header class="panel-heading"> 开放配置<a href="#" class="pull-right">编辑</a></li></header>',
		'      			  <table class="table table-bordered table-striped" style="width:100%">',
		'      			      <tbody>',
		'                        <tr><th><code>API名称</code></th><td>{API_NAME}</td><th><code>状态</code></th><td>{STATE}</td><th><code>最新更新时间</code></th><td>{STATE_DATE}</td><tr>',
		'                        <tr><th><code>是否要申请</code></th>{API_AUTH_TYPE}<td>Y</td><th><code>业务类别</code></th><td>{BUSI_TYPE}</td><th><code>版本号</code></th><td>{VERSEQ}</td><tr>',
		'      			  		 <tr><th><code>访问地址</code></th><td colspan="5" >{url}</td><tr>',
		'      			  		 <tr><th><code>授权给</code></th><td colspan="5" ><a href="#">选择</a></td><tr>',
		'      			  </table>',
		'      			  <header class="panel-heading"> 输入参数设置<a href="#" class="pull-right">新增</a></header>',
		'      			  <div id="{apiid}_in_fieldset" style="min-height:30px"></div>',
		'      			  <header class="panel-heading"> 输出参数设置<a href="#" class="pull-right">新增</a></header>',
		'      			  <div id="{apiid}_out_fieldset" style="min-height:30px"></div>',
		'      			  </div>',
		'</div>'].join("");

	var refApiContent = "myTabContent", refApiList = "refApiList";

	var listHtml = "", apibodyHtml = "";
	for (var i = 0; i < dsApiList.getCount(); i++) {
		var r = dsApiList.getAt(i);
		listHtml += listtpl.replace("{apitype}", r.get("BUSI_TYPE"))
			.replace("{apiid}", r.get("API_ID"))
			.replace("{apname}", r.get("API_NAME"))
			.replace("{REMARK}", r.get("REMARK"));
		apibodyHtml += apibodyTpl.replaceAll("{apiid}", r.get("API_ID"))
			.replace("{url}", "https://yourIp:port/openapi/" + r.get("API_ID"))
			.replace("{API_NAME}", r.get("API_NAME"))
			.replace("{STATE_DATE}", r.get("STATE_DATE"))
			.replace("{STATE}", r.get("STATE"))
			.replace("{REMARK}", r.get("REMARK"))
			.replace("{VERSEQ}", r.get("VERSEQ"))
			.replace("{BUSI_TYPE}", r.get("BUSI_TYPE"))
			.replace("{API_AUTH_TYPE}", r.get("API_AUTH_TYPE"))
			.replace("{REMARK}", r.get("REMARK"));
	}
	;
	$("#" + refApiList).empty().append(listHtml);
	$("#" + refApiContent).empty().append(apibodyHtml);
	$("#" + refApiList + " a").click(function () {
		var curApiId = ($(this).attr("href"));
		if (!curApiId) return false;
		curApiId = curApiId.replace("#", "");
		buildApiInPara(curApiId);
		buildApiOutPara(curApiId);
	});
	$("#" + refApiList + " a:first").click();
};

var registerNewApi = function () {
	var afterOK = function (fieldVals) {
		var r = dsApiList.getNewRecord();
		r.set("API_ID", fieldVals.API_ID || ai.guid());
		r.set("XMLID", fieldVals.API_ID || ai.guid());
		r.set("BUILD_TYPE", "OPENMODEL");
		r.set("API_AUTH_TYPE", fieldVals.API_AUTH_TYPE || "免申请");
		r.set("BUILD_PARA", xmlid);
		r.set("API_NAME", fieldVals.API_ID);
		r.set("API_NAME_ZH", fieldVals.API_NAME_ZH);
		r.set("REMARK", fieldVals.REMARK);
		r.set("BUSI_TYPE", fieldVals.BUSI_TYPE);

		r.set("CREATER", _UserInfo.username);
		r.set("STATE", '新建');
		r.set("EFF_DATE", new Date());
		r.set("STATE_DATE", new Date());
		r.set("VERSEQ", 1);
		r.set("CURDUTYER", _UserInfo.username);
		dsApiList.add(r);
		dsApiList.commit();
		buildApiInstance();
	};
	var formcfg = ({
		title: '新建开放模型', lock: true, id: 'baseInfoForm',
		// store: dsApiList,
		fieldChange: function (fieldName, newVal) {
		},//API_ID,API_NAME,API_NAME_ZH,API_AUTH_TYPE,TOPICCODE,DBNAME,TABLE_NAME,REMARK,BUSI_TYPE,BUILD_TYPE,BUILD_PARA,XMLID,SAMPLE_CODE,APP_CASE,CREATER,EFF_DATE,STATE,STATE_DATE,CURDUTYER,VERSEQ,SQLTEXT
		items: [{type: 'text', label: 'API编号', fieldName: 'API_ID', value: "", notNull: 'N', tip: '取一个有意义的名称'},
			{type: 'text', label: 'API名称', fieldName: 'API_NAME_ZH', value: "", notNull: 'Y'},
			{type: 'combox', label: '业务类别', fieldName: 'BUSI_TYPE', notNull: 'Y', storesql: '客户,用户,财务,渠道,品牌'},
			{type: 'combox', label: '权限类型', fieldName: 'API_AUTH_TYPE', notNull: 'Y', storesql: '公共数据,敏感数据'},
			{type: 'textarea', label: '备注', fieldName: 'REMARK', notNull: 'Y'}
		]
	});
	ai.showDialogForm(formcfg, null, afterOK);
}